<?php
namespace Core\Common\Model;

use Core\Common\Component\Cache\Cache;
use Core\Common\Helper\CacheLoader;
use Core\Common\Model\BaseModel;
use Illuminate\Database\Eloquent\Builder;

/**
 * 带分表的Model基类
 * Class AbstractDynamicModel
 * @package App\Model
 * @method static DynamicBuilder dynamic($name)
 */
abstract class AbstractDynamicModel extends BaseModel
{
    use ModelCachable;

    /**
     * 关闭自增主键
     * @var bool
     */
    public $incrementing = false;

    /**
     * 替换Model的QueryBuilder，使其附带缓存能力
     * @param Builder $query
     * @return CachedBuilder
     */
    public function newEloquentBuilder($query)
    {
        $options = [
            'prefix' => $this->cachePrefix ?: $this->defaultCachePrefix(),
            'ttl' => CachedBuilder::DEFAULT_TTL
        ];
        $cacheLoader = new CacheLoader(Cache::store($this->cacheDriver), $options);

        return new DynamicBuilder($query, $cacheLoader);
    }

    /**
     * 根据属性设置分表
     * @param array $attributes
     */
    abstract public static function getTableByAttr($attributes);

    /**
     * 生成主键
     * @return string
     */
    abstract protected function newPrimaryKey();

    public function getTable()
    {
        return $this->table;
    }

    public function save(array $options = [])
    {
        $this->setTable(
            static::getTableByAttr($this->attributes)
        );
        return parent::save($options);
    }

    protected function performInsert(Builder $query)
    {
        $key = $this->getKeyName();

        if (!array_key_exists($key, $this->attributes)) {
            $this->setAttribute($key, $this->newPrimaryKey());
        }

        return parent::performInsert($query);
    }
}